package com.lanmao.emc.strategy.impl;

import com.lanmao.emc.enums.UpgradeType;
import com.lanmao.emc.utils.EsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 描述：保持索引强一致性，升级后索引名不变，两次迁移，性能差
 *
 * @author lanmao
 * @since 2024年11月12日 20:36
 */
@Slf4j
@Service
public class TwoMigrationStrategyImpl extends UpgradeStrategyImpl {
    @Override
    public UpgradeType getUpgradeType() {
        return UpgradeType.TWO_MIGRATION;
    }

    @Override
    int upgradeIndex(String indexName, String json, String bakIndexName) {
        try {
            if (EsUtils.existsIndex(indexName)) {
                //创建A_back
                EsUtils.addIndex(bakIndexName, json);
                log.info("create index {} success", bakIndexName);
                //备份A_back
                long count = EsUtils.reindexAndGetCount(indexName, bakIndexName);
                log.info("reindex index {} success,count :{}", bakIndexName, count);
                //删除A
                EsUtils.delIndex(indexName);
                log.info("delete index {} success", indexName);

                //创建A
                EsUtils.addIndex(indexName, json);
                log.info("create index {} success", indexName);

                //数据迁移到A
                count = EsUtils.reindexAndGetCount(bakIndexName, indexName);
                log.info("reindex index {} success,count :{}", indexName, count);
                //删除A_back
                EsUtils.delIndex(bakIndexName);
                log.info("delete index {} success", bakIndexName);

            } else {
                EsUtils.addIndex(indexName, json);
                log.info("create index {} success", indexName);
            }
        } catch (Exception e) {
            return handleException(indexName, indexName, bakIndexName, e);
        }
        return 1;
    }
}